package com.sdk.utill;

import autovalue.shaded.com.google.common.common.base.Joiner;
import com.alibaba.fastjson.JSON;
import com.sdk.ks.KSConfig;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public final class KSUtil {
   public static String calcSign(Map<String, Object> signParamsMap) {
      signParamsMap.put("app_id", KSConfig.appId);
      Map<String, Object> trimmedParamMap = signParamsMap.entrySet().stream().filter((item) -> StringUtils.isNotBlank(item.getKey()) && ObjectUtils.isNotEmpty(item.getValue())).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
      Map<String, Object> sortedParamMap = trimmedParamMap.entrySet().stream().sorted(Entry.comparingByKey()).collect(Collectors.toMap(Entry::getKey, Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
      String paramStr = Joiner.on("&").withKeyValueSeparator("=").join(sortedParamMap.entrySet());
      String signStr = paramStr + KSConfig.ksConfigMap.get(KSConfig.appId);
      return DigestUtils.md5Hex(signStr);
   }

   public static Map<String, Object> createRequest(
           String roomCode, String actionType, String moduleType, String pushType, Map<String, Object> data
   ) {
       Map<String, Object> signParams = new HashMap<>();
       if (roomCode != null && !roomCode.isEmpty()) {
           signParams.put("roomCode", roomCode);
       }

       if (actionType != null && !actionType.isEmpty()) {
           signParams.put("actionType", actionType);
       }

       long time = System.currentTimeMillis();
       signParams.put("timestamp", time);
       if (moduleType != null && !moduleType.isEmpty()) {
           signParams.put("moduleType", moduleType);
       }

       if (pushType != null && !pushType.isEmpty()) {
           signParams.put("pushType", pushType);
       }

       if (data != null) {
           signParams.put("data", JSON.toJSONString(data));
       }

       String sign = calcSign(signParams);
       signParams.put("sign", sign);
       return signParams;
   }
}
